package com.hilihili.controller.personalHomepageComponent;

import com.hilihili.domain.entity.Carousel;
import com.hilihili.domain.entity.Favorites;
import com.hilihili.domain.entity.FavoritesVideoList;
import com.hilihili.domain.entity.UserStars;
import com.hilihili.service.IFavoritesService;
import com.hilihili.service.IFavoritesVideoListService;
import com.hilihili.service.IUserStarsService;
import com.hilihili.util.PictureMD5Util;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * @Author xhc
 * @Date 2024/1/26 11:17
 * @Version 1.0
 */
@RestController
@RequestMapping("/hilihili/favorites")
public class FavoritesController {
    @Autowired
    private IFavoritesService favoritesService;
    @Autowired
    private IFavoritesVideoListService favoritesVideoListService;
    @Value("${pictureUpload.source}")
    private String uploadPath;
    /**
     *
     * 查询我的创建的收藏夹
     * @param createAt 用户id
     * @return
     */
    @GetMapping("/list/{createAt}")
    public AjaxResult list(@PathVariable("createAt")Long createAt){
        // TODO 在查询时，若收藏夹没有设置封面并且收藏夹中有至少一个视频，则获取收藏夹中第一个视频的图片作为封面
        List<Favorites> favorites = favoritesService.selectFavoritesList(createAt);
        favorites.forEach(item -> {
            if (item.getFavoritesCover() != null && !"".equals(item.getFavoritesCover())){
                item.setImgBase64(PictureMD5Util.convertImageToBase64(uploadPath + item.getFavoritesCover()));
            }
        });
        return AjaxResult.success(favorites);
    }

    /**
     * 视频页，点击收藏时查询收藏夹list
     * @param videoId
     * @return
     */
    @GetMapping("/selectFavoritesChecked/{videoId}")
    public AjaxResult selectFavoritesChecked(@PathVariable("videoId")Long videoId){
        Long userId = SecurityUtils.getUserId();
        // 查询该视频是否被收藏
        List<FavoritesVideoList> favoritesVideoLists = favoritesVideoListService.selectListByUserIdAndVideoId(userId, videoId);
        List<Favorites> favorites = favoritesService.selectFavoritesList(userId);
        List<Favorites> favoritesTemp = new ArrayList<>();
        if (favoritesVideoLists.size() > 0){
            for (int i = favorites.size() -1; i >= 0; i--) {
                for (int i1 = 0; i1 < favoritesVideoLists.size(); i1++) {
                    Long id = favorites.get(i).getId();
                    Long favoritesId = favoritesVideoLists.get(i1).getFavoritesId();
                    if (id.equals(favoritesId)){
                        favorites.get(i).setChecked("checked");
                        favoritesTemp.add(favorites.get(i));
                        favorites.remove(i);
                    }
                }
            }
        }
        for (int i = 0; i < favoritesTemp.size(); i++) {
            favorites.add(0,favoritesTemp.get(i));
        }

        return AjaxResult.success(favorites);
    }


    /**
     * 删除收藏夹
     * @param id
     * @return
     */
    @GetMapping("/deleteFavorites/{id}")
    public AjaxResult deleteFavorites(@PathVariable("id")Long id){
        int i = favoritesService.deleteFavorites(id);
        if (i > 0){
            return AjaxResult.success("删除收藏夹成功");
        }else {
            return AjaxResult.error("删除收藏夹失败");
        }
    }

    /**
     * 个人主页中 新增、修改收藏夹
     * @param favorites
     * @return
     */
    @PostMapping("/updateFavorites")
    public AjaxResult updateFavorites(@RequestBody Favorites favorites){
        if (favorites == null) return AjaxResult.error("错误参数");
        if (Objects.isNull(favorites.getId())){
            // 新增
            if (favorites.getImgBase64() != null) {
                //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
                String fileName = UUID.randomUUID().toString() + ".png";
                //创建一个目录对象
                String basePath = uploadPath + SecurityUtils.getUserId() + "\\" + "favoritesCover\\";
                Boolean aBoolean = PictureMD5Util.generatePicture(favorites.getImgBase64(), basePath + fileName);
                if (!aBoolean){
                    return AjaxResult.error("收藏夹图片保存失败");
                }
                favorites.setFavoritesCover(SecurityUtils.getUserId() + "\\" + "favoritesCover\\" + fileName);
            }
            favorites.setFavoritesRank(favorites.getRank());
            favorites.setCreateAt(SecurityUtils.getUserId());
            favorites.setCreateTime(new Date());
            int i = favoritesService.saveFavorites(favorites);
            return AjaxResult.success("新增收藏夹成功");
        }else {
            // 修改
            Boolean aBoolean = favoritesService.updateFavorites(favorites, uploadPath);
            if (!aBoolean){
                return AjaxResult.error("收藏夹图片保存失败");
            }
            return AjaxResult.success("编辑收藏夹成功");
        }
    }

    /**
     * 改变我的收藏夹排序
     * @param ids
     * @return
     */
    @GetMapping("/updateFavoritesRank")
    public AjaxResult updateFavoritesRank(String ids){
        String[] strids = ids.split(",");
        favoritesService.updateFavoritesRank(strids);
        return AjaxResult.success("修改成功");
    }

    /**
     * 初始化 “新增默认收藏夹”
     * @param
     * @return
     */
    @GetMapping("/addDefaultFavorites/{createAt}")
    public AjaxResult addDefaultFavorites(@PathVariable("createAt") Long createAt){
        Long userId = SecurityUtils.getUserId();
        if (!createAt.equals(userId)){
            // TODO 直接访问连接为什么可以查到？
            return AjaxResult.error("用户不一致错误");
        }
        // 查询是否存在默认收藏夹
        List<Favorites> favoritesList = favoritesService.selectDefaultFavorites(createAt);
        if (favoritesList.size()==0){
            // 新增
            Favorites favorites = new Favorites();
            favorites.setFavoritesName("默认收藏夹");
            favorites.setFavoritesRank(1);
            favorites.setFavoritesPublic(1);
            favorites.setCreateAt(SecurityUtils.getUserId());
            favorites.setCreateTime(new Date());
            int i = favoritesService.saveFavorites(favorites);
            return AjaxResult.success("新增收藏夹成功");
        }
        return AjaxResult.error("默认收藏夹已存在");
    }


    @PostMapping("/uploadFavoritesCover")
    public AjaxResult uploadFavoritesCover(@RequestParam("image")MultipartFile file) {
        //原始文件名
        String originalFilename = file.getOriginalFilename();//xxx.png
        //对原始名进行截取"."后面的字符
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//.png
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        //创建一个目录对象
        String basePath = uploadPath + SecurityUtils.getUserId() + "\\" + "favoritesCover\\";
        File dir = new File(basePath);
        //判断当前目录是否存在：目录不存在，需要创建
        if(!dir.exists()) dir.mkdirs();
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + fileName));
            return AjaxResult.success("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
           return AjaxResult.error("上传失败");
        }

    }
}
